#include "tcp_client.h"

static const char *TAG = "TCP";
static const char *payload = "Message from ESP32 ";

void tcp_client_task(void *pvParameters)
{
    char rx_buffer[1024];
    char tx_buffer[1024];
    char addr_str[128];
    int addr_family;
    int ip_protocol;
    int wifi_eventbits = 0;
    cJSON *root;
    cJSON *results;
    cJSON *last_update;
    cJSON *now_weather;
    cJSON *loc_json, *daily_json;
    cJSON *forecast_json;
    char *loc_tmp, *weather_tmp, *update_tmp;
    char send_cmd[] = "GET https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=%s&unit=c\r\n";
    while (1)
    {
        vTaskDelay(2000 / portTICK_PERIOD_MS);

#ifdef CONFIG_EXAMPLE_IPV4
        struct sockaddr_in dest_addr;
        dest_addr.sin_addr.s_addr = inet_addr(HOST_IP_ADDR);
        dest_addr.sin_family = AF_INET;
        dest_addr.sin_port = htons(PORT);
        addr_family = AF_INET;
        ip_protocol = IPPROTO_IP;
        inet_ntoa_r(dest_addr.sin_addr, addr_str, sizeof(addr_str) - 1);
#else // IPV6
        struct sockaddr_in6 dest_addr = {0};
        inet6_aton(HOST_IP_ADDR, &dest_addr.sin6_addr);
        dest_addr.sin6_family = AF_INET6;
        dest_addr.sin6_port = htons(PORT);
        // Setting scope_id to the connecting interface for correct routing if IPv6 Local Link supplied
        dest_addr.sin6_scope_id = esp_netif_get_netif_impl_index(EXAMPLE_INTERFACE);
        addr_family = AF_INET6;
        ip_protocol = IPPROTO_IPV6;
        inet6_ntoa_r(dest_addr.sin6_addr, addr_str, sizeof(addr_str) - 1);
#endif

        int sock = socket(addr_family, SOCK_STREAM, ip_protocol);
        if (sock < 0)
        {
            ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Socket created, connecting to %s:%d", HOST_IP_ADDR, PORT);

        int err = connect(sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
        if (err != 0)
        {
            ESP_LOGE(TAG, "Socket unable to connect: errno %d", errno);
            break;
        }
        ESP_LOGI(TAG, "Successfully connected");
        memset(tx_buffer, 0, sizeof(tx_buffer));
        sprintf(tx_buffer, send_cmd, PRIVATE_KEY, "ningbo", LANGUAGE);
        while (1)
        {
            int err = send(sock, tx_buffer, strlen(tx_buffer), 0);
            if (err < 0)
            {
                ESP_LOGE(TAG, "Error occurred during sending: errno %d", errno);
                break;
            }

            int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
            // Error occurred during receiving
            if (len < 0)
            {
                ESP_LOGE(TAG, "recv failed: errno %d", errno);
                break;
            }
            // Data received
            else
            {
                rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
                ESP_LOGI(TAG, "Received %d bytes from %s:", len, addr_str);
                ESP_LOGI(TAG, "%s", rx_buffer);
                //json数据解析
                root = cJSON_Parse((const char *)rx_buffer);
                if (root)
                {
                    printf("json is right\n");
                    results = cJSON_GetObjectItem(root, "results");
                    results = cJSON_GetArrayItem(results, 0);
                    if (results)
                    {
                        loc_json = cJSON_GetObjectItem(results, "location");
                        if (loc_json)
                        {
                            loc_tmp = cJSON_GetObjectItem(loc_json, "id")->valuestring;
                            printf("id = %s\n", loc_tmp);
                            loc_tmp = cJSON_GetObjectItem(loc_json, "country")->valuestring;
                            printf("country = %s\n", loc_tmp);
                            loc_tmp = cJSON_GetObjectItem(loc_json, "country")->valuestring;
                            printf("country = %s\n", loc_tmp);
                        }
                        now_weather = cJSON_GetObjectItem(results, "now");
                        if (now_weather)
                        {
                            loc_tmp = cJSON_GetObjectItem(now_weather, "temperature")->valuestring;
                            printf("temp = %s\n", loc_tmp); //获取温度
                            loc_tmp = cJSON_GetObjectItem(now_weather, "text")->valuestring;
                            printf("text = %s\n", loc_tmp);
                        }
                    }
                }
                cJSON_Delete(root);
            }
            break;
        }
        shutdown(sock, 0);
        close(sock);
        vTaskDelay(20000 / portTICK_PERIOD_MS);
    }
    vTaskDelete(NULL);
}